import type { Directive } from 'vue'

let wrapperDom: HTMLElement
let dragStart = false
const dragInfo = { x: 0, y: 0 }

const handleMousemove = (ev: MouseEvent) => {
  if (!dragStart) return
  const x = ev.x - dragInfo.x
  let y = ev.y - dragInfo.y
  y = y <= 0 ? 0 : y
  wrapperDom.style.left = `${x}px`
  wrapperDom.style.top = `${y}px`
}
const handleMouseup = () => {
  dragStart = false
  document.removeEventListener('mousemove', handleMousemove)
  document.removeEventListener('mouseup', handleMouseup)
}

const handleMousedown = (ev: MouseEvent) => {
  if (!wrapperDom) return
  const { left, top } = wrapperDom.getBoundingClientRect()
  dragInfo.x = ev.x - left
  dragInfo.y = ev.y - top
  dragStart = true
  document.addEventListener('mousemove', handleMousemove)
  document.addEventListener('mouseup', handleMouseup)
}

export default {
  mounted(el: HTMLElement) {
    wrapperDom = el
    el.addEventListener('mousedown', handleMousedown)
  },
  beforeUnmount(el: HTMLElement) {
    el.removeEventListener('mousedown', handleMousedown)
  }
} as Directive
